package mysql

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/Go-SQL-Driver/MySQL"
	"study/testproject/source/util/list"
)

func GetDBConn() (rdb *sql.DB, err error) {
	db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/webmsg_db")
	if err != nil {
		fmt.Println("GetConn error:", err)
		return db, err
	}
	return db, nil
}
func Exec(sql string, data ...interface{}) (row int, err error) {
	db, err0 := GetDBConn()
	defer db.Close()
	if err0 != nil {
		errorPrint(err0)
	}

	stmt, err1 := db.Prepare(sql)
	defer stmt.Close()
	if err1 != nil {
		errorPrint(err1)
	}

	result, err2 := stmt.Exec(data...)
	if err2 != nil {
		errorPrint(err2)
	}
	_, err3 := result.RowsAffected()
	if err3 != nil {
		errorPrint(err3)
	}
	id, _ := result.LastInsertId()
	return int(id), nil
}

func errorPrint(err error) {
	fmt.Println("error=", err)
}
func GetBySqlToListMap(sql string) list.List {
	db, conerr := GetDBConn()
	defer db.Close()
	if conerr != nil {
		fmt.Println(conerr)
	}

	rows, qurerr := db.Query(sql)
	defer rows.Close()
	if qurerr != nil {
		fmt.Println(qurerr)
	}
	columns, _ := rows.Columns()
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for j := range values {
		scanArgs[j] = &values[j]
	}
	lst := list.New()
	//tmpBean := reflect.TypeOf(bean)
	for rows.Next() {
		err := rows.Scan(scanArgs...)
		if err != nil {
			fmt.Println(err)
		}
		record := make(map[string]string)
		for i, col := range values {
			if col != nil {
				record[columns[i]] = string(col.([]byte))
			} else {
				record[columns[i]] = ""
			}
		}
		lst.Add(record)
	}
	return lst
}

func ToJson(data list.List) string {
	bye, err := json.Marshal(data.Values())
	if err != nil {
		fmt.Println(err)
	}
	return string(bye)
}
